import { debounce } from 'lodash-es';

/**
 * 基础配置: 主要应用于axios实例
 */
export const BASE_CONFIG = {
  base: import.meta.env.VITE_BASE_URL,
  contentType: 'application/json',
  timeout: 60000
};

/**
 * 返回数据结构
 */
export const RESPONSE_CONFIG = {
  code: 'code',
  msg: 'message',
  successCode: 200
}

const debounceToLogin = debounce(resetStateAndToLogin, 1500, {
  leading: true
});
const debounceNotice = debounce(notice, 1500, {
  leading: true
});

export const ERROR_STATUS_CODE_MAP: ERROR_STATUS_CODE = {
  401: {
    text: '登录失效，请重新登录',
    handler: debounceToLogin
  },
  403: {
    text: '请重新登录',
    handler: debounceToLogin
  },
  default: {
    text: '请求失败',
    handler: debounceNotice
  }
};

function notice(description: string) {
  AntNotification.error({
    message: '请求失败',
    description
  });
}

function resetStateAndToLogin(message: string) {
  notice(message);
  useUserStore().userlogout();
}

interface ErrHandler {
  text: string;
  handler(err?: unknown): void;
}

type ERROR_STATUS_CODE = {
  [key: number | string]: ErrHandler;
};
